<?php 
/**
 * @author Rewrite by Maowl
 *
 */
class AccessControlFilter extends CAccessControlFilter {
	/**
	 * @param array $rules list of access rules.
	 */
	private $_rules=array();
	/**
	 * @return array list of access rules.
	 */
	public function getRules()
	{
		return $this->_rules;
	}
	
	public function setRules($rules)
	{
		foreach($rules as $rule){
			if(is_array($rule) && isset($rule[0])){
				$r = new AccessRule;
				$r->allow = ($rule[0]==='allow');
				
				foreach(array_slice($rule,1) as $name=>$value){
					if(in_array($name, array('expression', 'roles', 'actions', 'message', 'ajax_denyinfo', 'redirect')))
						$r->$name=$value;
					else
						$r->$name=array_map('strtolower',$value);
				}
				$this->_rules[]=$r;
			}
		}
	}
	
	protected function accessDenied($user,$message)
	{
		$user->loginRequired();
	}
	
	protected function preFilter($filterChain)
	{
		$app=Yii::app();
		$request=$app->getRequest();
		$user=$app->getUser();
		$verb=$request->getRequestType();
		$ip=$request->getUserHostAddress();

		foreach($this->getRules() as $rule){
			$allow = $rule->isUserAllowed($user, $filterChain->controller, $filterChain->action, $ip, $verb);
			if($allow > 0){
				break;
			}else if($allow == 0){	// action do not match
				continue;
			}else{
				if($app->request->getIsAjaxRequest()){
					echo json_encode($rule->ajax_denyinfo);
					exit;
					return false;
				}else if($rule->redirect){
					//$app->user->loginUrl = $rule->redirect;
					$app->request->redirect($rule->redirect);
				}
				$this->accessDenied($user, $this->resolveErrorMessage($rule));
				return false;
			}
		}
		return true;
	}
}
